//
//  AddViewController.m
//  收纳
//
//  Created by  on 2022/10/28.
//

#import "AddViewController.h"
#import "SaveCell.h"
#import "AddSignCell.h"
#import "MineCell.h"
#import "AddImgCell.h"

@interface AddViewController ()
@property (nonatomic, strong) NSArray *config;
@property (nonatomic, strong) NSArray *titles;
@property (nonatomic, strong) NSArray *contents;
@property (nonatomic, strong) NSMutableArray *types;
@property (nonatomic, assign) CGFloat offsetY;

@end

@implementation AddViewController
- (void)viewDidLoad{
    [super viewDidLoad];
    [self update];
}
- (void)initUI{
    self.title = LS(@"新增物品");
    [self.tableView registerNib:[MineCell nib] forCellReuseIdentifier:[MineCell ID]];
    [self.tableView registerNib:[AddImgCell nib] forCellReuseIdentifier:[AddImgCell ID]];
    [self.tableView registerNib:[AddSignCell nib] forCellReuseIdentifier:[AddSignCell ID]];
    [self.tableView registerNib:[SaveCell nib] forCellReuseIdentifier:[SaveCell ID]];
    
    self.tableView.c_left.equalTo(self.view).coffset(20);
    self.tableView.c_right.equalTo(self.view).coffset(-20);
    self.tableView.c_top.equalTo(self.view).coffset(0);
    self.tableView.c_bottom.equalTo(self.view).coffset(0);
}
- (void)update{
    NSString *date = [NSDate transToDate:@"yyyy.MM.dd" :self.model.stamp];
    if (self.model.isContainer == NO) {
        self.title = LS(@"新增物品");
        self.config = @[@"1",@"0",@"1",@"3",@"1",@"1",@"0",@"0"];
        self.titles = @[@"物品名称",@"0",@"选择容器",@"设置为容器",@"价格",@"购买时间",@"0",@"0"];
        self.contents = @[self.model.name,@"",self.model.container,self.model.isContainer?@"1":@"0",self.model.money,date,@"",@"",@""];
        [GoodsTool find:YES complete:^(NSMutableArray<Goods *> * _Nonnull result) {
            self.types = [NSMutableArray array];
            for (Goods *model in result) {
                [self.types addObject:model.name];
            }
        }];
    }else{
        self.title = LS(@"新增容器");
        self.config = @[@"1",@"0",@"3",@"1",@"1",@"0",@"0"];
        self.titles = @[@"容器名称",@"0",@"设置为容器",@"价格",@"购买时间",@"0",@"0"];
        self.contents = @[self.model.name,@"",self.model.isContainer?@"1":@"0",self.model.money,date,@"",@"",@""];
    }
    [self.tableView reloadData];
}
#pragma mark - 保存
- (void)save{
    if (self.model.name.length <= 0) {
        return [CCHud msg:@"名称不能为空"];
    }else if (self.model.imgs.count <= 0){
        return [CCHud msg:@"图片不能为空"];
    }else if (self.model.money.length <= 0){
        return [CCHud msg:@"价格不能为空"];
    }else if (self.model.signArray.count <= 0){
        return [CCHud msg:@"标签不能为空"];
    }else if (self.model.container.length <= 0 && !self.model.isContainer){
        return [CCHud msg:@"选择的容器不能为空"];
    }else if (self.model.remark.length <= 0 && self.model.isContainer){
        return [CCHud msg:@"备注不能为空"];
    }
    for (NSString *name in self.types) {
        if ([self.model.name isEqualToString:name]) {
            return [self alert:@"提示" :[NSString stringWithFormat:@"容器<%@> 已经存在，确定新增重复的容器吗?",name] :nil :^{
                [GoodsTool update:self.model complete:^(BOOL success) {
                    [self backBtnAction];
                }];
            }];
        }
    }
    [GoodsTool update:self.model complete:^(BOOL success) {
        [self backBtnAction];
    }];
}

//- (void)methodKeyboardShow:(NSNotification*)notifi
//{
//    NSDictionary *userInfo = [notifi userInfo];
//    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
//    CGFloat keyboardHeight = [aValue CGRectValue].size.height;
//    CGFloat time = [notifi.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
//    CGFloat maxY = 0;
//    UIView *view = [self firstResponder:self.view];
//    if ([view isKindOfClass:NSClassFromString(@"WKContentView")])
//    {
//        return;
//    }
//    maxY =  CGRectGetMaxY([view convertRect:view.bounds toView:[[[UIApplication sharedApplication] delegate] window]]);
//    CGFloat map = SCREEN_HEIGHT - maxY - keyboardHeight;
//    if (ceil(map) < 0)
//    {
//       self.offsetY = self.tableView.contentOffset.y;
//        [UIView animateWithDuration:time animations:^{
//            [self.tableView setContentOffset:CGPointMake(0, self.tableView.contentOffset.y - map) animated:YES];
//        }];
//    }
//}
//- (void)methodKeyboardHidden:(NSNotification*)notifi
//{
//    CGFloat time = [notifi.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
//    [UIView animateWithDuration:time animations:^{
//        [self.tableView setContentOffset:CGPointMake(0, self.offsetY) animated:YES];
//    }];
//}
#pragma mark - UIImagePickerControllerDelegate / UINavigationControllerDelegate
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info{
    UIImage *img = info[UIImagePickerControllerEditedImage];
    NSData *data = UIImageJPEGRepresentation(img, 0.5);
    if (self.model) {
        [self.model.imgs addObject:data];
    }
    [self update];
    [picker dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.model.isContainer ? 7 : 8;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WS(self)
    if (indexPath.section == 1) {
        AddImgCell *cell = [tableView dequeueReusableCellWithIdentifier:[AddImgCell ID]];
        cell.model = self.model;
        cell.block = ^{
            [weakself takePic];
        };
        return cell;
    }else if ((indexPath.section == 6 && !self.model.isContainer) || (self.model.isContainer && indexPath.section == 5)){
        AddSignCell *cell = [tableView dequeueReusableCellWithIdentifier:[AddSignCell ID]];
        cell.model = self.model;
        cell.block = ^{
            [InputViewController show:^(NSString * _Nonnull string) {
                [weakself.model.signArray addObject:string];
                [weakself update];
            }];
        };
        return cell;
    }else if ((indexPath.section == 7 && !self.model.isContainer)  || (self.model.isContainer && indexPath.section == 6)){
        SaveCell *cell = [tableView dequeueReusableCellWithIdentifier:[SaveCell ID]];
        cell.model = self.model;
        cell.block = ^{
            [weakself save];
        };
        return cell;
    }else{
        MineCell *cell = [tableView dequeueReusableCellWithIdentifier:[MineCell ID]];
        cell.dict = @{self.titles[indexPath.section]:self.contents[indexPath.section]};
        cell.type = [self.config[indexPath.section] integerValue];
        cell.block = ^(BOOL on) {
            weakself.model.isContainer = on;
            [weakself update];
        };
        return cell;
    }
}
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 20;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 20)];
    view.backgroundColor = [UIColor clearColor];
    return view;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    WS(self)
    NSString *title = self.titles[indexPath.section];
    if ([title isEqualToString:@"购买时间"]) {
        JZBDateViewController *vc = [JZBDateViewController new];
        vc.stamp = self.model.stamp;
        vc.selectBlock = ^(int stamp) {
            weakself.model.stamp = stamp;
            [weakself update];
        };
        [self presentViewController:vc animated:NO completion:nil];
    }else if ([title isEqualToString:@"选择容器"] && self.model.isContainer == NO){
        if (self.types.count <= 0) {
            return [self alert:@"提示" :@"您当前未添加任何容器，请先添加一个容器" :nil :nil];
        }
        PickViewController *vc = [PickViewController new];
        vc.array = self.types;
        vc.block = ^(NSString * _Nonnull string) {
            weakself.model.container = string;
            [weakself update];
        };
        [self presentViewController:vc animated:NO completion:nil];
    }else if ([title isEqualToString:@"物品名称"] || [title isEqualToString:@"容器名称"]){
        [InputViewController show:^(NSString * _Nonnull string) {
            weakself.model.name = string;
            [weakself update];
        }];
    }else if ([title isEqualToString:@"价格"]){
        [InputViewController show:^(NSString * _Nonnull string) {
            if (![string isFloat] && ![string isNumber]) {
                return [CCHud msg:@"格式错误"];
            }
            weakself.model.money = string;
            [weakself update];
        }];
    }
}
@end

